package org.fanjr.simplify.zk.server;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

public class ZkPropertiesUtils {

	private final static Set<String> KEY_SET = new HashSet<>();

	static {
		Method[] methods = QuorumPeerConfig.class.getMethods();
		for (Method method : methods) {
			String methodName = method.getName();
			if (methodName.startsWith("get") && !methodName.equals("getClass")) {
				StringBuilder sb = new StringBuilder();
				sb.append(Character.toLowerCase(methodName.charAt(3)));
				sb.append(methodName.substring(4));
				KEY_SET.add(sb.toString());
			}
		}
		KEY_SET.add("clientPort");
	}

	public static Properties getZkProperties(String perfix, Environment environment) {
		Properties target = new Properties();
		for (String key : KEY_SET) {
			String nKey = perfix + key;
			String val = System.getProperty(nKey);
			if (StringUtils.hasText(val)) {
				target.put(key, val);
			} else {
				val = environment.getProperty(nKey);
				if (StringUtils.hasText(val)) {
					target.put(key, val);
				}
			}
		}
		return target;
	}

	public static void main(String[] args) {
		KEY_SET.forEach((val) -> System.out.println("zookeeper." + val));
	}

}
